﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using AForge.Video;
using AForge.Video.DirectShow;
using LogLib;

namespace Camera
{
    public class Camera
    {
        // list of video devices
        private FilterInfoCollection _videoDevices;
        private int _camIndex = -1;
        private VideoCaptureDevice _videoSource;
        public delegate void GetCameraImageData(object sender, NewFrameEventArgs eventArgs);
        public event GetCameraImageData newFrame;    //声明事件
        public bool bStartCameras = false;

        private string _error = "";
        public string Error
        {
            get { return _error; }
        }

        public int InitCamera(ref string camName,ref int camIndex)
        {
            _error = "";
            _videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);
            if (_videoDevices.Count == 0)
            {
                _error = "计算机未连接任何图像设备，请检查镜头设备是否连接.";
                return -1;
            }
            if (camIndex>=0)
            {
                camName = _videoDevices[0].Name;
                Log.WriteAsync("CameraName:" + camName);
                _camIndex = camIndex;
                return 0;
            }
            else
            {
                for (int i = 1, n = _videoDevices.Count; i <= n; i++)
                {
                    if (camName == _videoDevices[i - 1].Name)
                    {
                        camIndex = i;
                        _camIndex = i;
                        return 0;
                    }
                }
            }
            _error = string.Format("指定的镜头设备未连接:{0}-{1}.", camIndex, camName);
            return -2;
        }

        public void StartCameras()
        {
            // create first video source
            if (!bStartCameras)
            {
                _videoSource = new VideoCaptureDevice(_videoDevices[_camIndex].MonikerString);
                _videoSource.NewFrame += GetNewFrame;
                _videoSource.Start();
                bStartCameras = true;
            }          
        }

        // Stop cameras
        public void StopCameras()
        {
            if (bStartCameras)
            {                
                _videoSource.NewFrame -= GetNewFrame;
                _videoSource.Stop();
                _videoSource.SignalToStop();
                _videoSource.WaitForStop();
                bStartCameras = false;
            }        
        }

        private void GetNewFrame(object sender, NewFrameEventArgs eventArgs)
        {
            if (newFrame != null) newFrame(null, eventArgs);
        }
   }
}
